package com.info.zhiduoduo.common.baidusdk;

import com.alibaba.fastjson.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.info.zhiduoduo.common.baidusdk.configs.BaiduSdkConfig;
import com.info.zhiduoduo.common.baidusdk.domain.OcrBankcardResult;
import com.info.zhiduoduo.common.baidusdk.domain.OcrIdcardResult;
import com.info.zhiduoduo.common.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class OcrService {

	@Autowired
	BaiduSdkConfig baiduSdkConfig;

	/**
	 * 银行卡识别
	 *
	 * @param imgFile
	 * @return
	 */
	public OcrBankcardResult recognizeBankcard(String imgFile) {
		// 传入可选参数调用接口
		AipOcr client = new AipOcr(baiduSdkConfig.getAppid(), baiduSdkConfig.getApikey(), baiduSdkConfig.getSecret());

		HashMap<String, String> options = new HashMap<String, String>();

		// 参数为本地路径
		JSONObject res = client.bankcard(imgFile, options);
		LogUtil.info("识别结果:" + res.toString());
		Object o = null;
		try {
			o = res.get("result");
		} catch (JSONException e) {
			//识别报错,没有返回result,直接返回null
			return null;
		}
		return JSON.parseObject(o.toString(), OcrBankcardResult.class);
	}

	/**
	 * 身份证识别
	 *
	 * @param imgFile
	 * @return
	 */
	public OcrIdcardResult recognizeIdcard(String imgFile, int idcardSide) {
		// 传入可选参数调用接口
		AipOcr client = new AipOcr(baiduSdkConfig.getAppid(), baiduSdkConfig.getApikey(), baiduSdkConfig.getSecret());

		HashMap<String, String> options = new HashMap<String, String>();

		// 参数为本地路径
		JSONObject res = client.idcard(imgFile, idcardSide == 0 ? "front" : "back", options);
		LogUtil.info("识别结果:" + res.toString());
		OcrIdcardResult result = null;
		try {
			JSONObject o = res.getJSONObject("words_result");
			result = new OcrIdcardResult().setIdno(o.getJSONObject("公民身份号码").getString("words"))
					.setName(o.getJSONObject("姓名").getString("words"))
					.setBirth(o.getJSONObject("出生").getString("words"))
					.setAddr(o.getJSONObject("住址").getString("words"))
					.setNationality(o.getJSONObject("民族").getString("words"))
					.setSex(o.getJSONObject("性别").getString("words"))
					.setAuthority(o.getJSONObject("签发机关").getString("words"))
					.setInvalidDate(o.getJSONObject("失效日期").getString("words"))
					.setIssueDate(o.getJSONObject("签发日期").getString("words"));
		} catch (JSONException e) {
			//识别报错,没有返回result,直接返回null
			return null;
		}
		return result;
	}

}
